package czk.concrent.enjoyModelWithNotLock.atomicIntergerArray.practice;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicIntegerArray;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;

/**
 * 流式思想的运用
 *
 * @Author:ChenZhangKun
 * @Date: 2020/12/16 22:29
 */
public class AtomicIntegerArrayDemo {
    public static void main(String[] args) {
        demo(() -> new AtomicIntegerArray(10),
                AtomicIntegerArray::length,
                (AtomicIntegerArray::getAndIncrement),
                System.out::println);
    }

    public static <T> void demo(Supplier<T> supplier,
                                Function<T, Integer> function, BiConsumer<T, Integer> biConsumer, Consumer<T> consumer) {
        // 拿到提供函数的值
        T array = supplier.get();
        // 拿到数组的长度
        Integer length = function.apply(array);
        // 创建线程集合
        List<Thread> list = new ArrayList<>(10);
        for (Integer i = 0; i < length; i++) {

            list.add(new Thread(() -> {
                for (int j = 0; j < 1000; j++) {
                    biConsumer.accept(array, j % length);
                }
            }));
        }
        // 启动线程
        list.forEach(Thread::start);
        // 等待线程执行完
        list.forEach(x -> {
            try {
                x.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        //
        consumer.accept(array);
    }
}
